package com.atom.module.mvvm.extren

import android.widget.RatingBar
import androidx.annotation.CheckResult
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.conflate

@CheckResult
@OptIn(ExperimentalCoroutinesApi::class)
 fun RatingBar.ratingChangeEvents()= callbackFlow<RatingChangeEvent> {
    checkMainThread()
    val listener = RatingBar.OnRatingBarChangeListener { ratingBar, rating, fromUser ->
        trySend(
            RatingChangeEvent(
                view = ratingBar,
                rating = rating,
                fromUser = fromUser
            )
        )
    }
    onRatingBarChangeListener = listener
    awaitClose { onRatingBarChangeListener = null }
}
    .conflate()
    .asInitialValueFlow {
        RatingChangeEvent(
            view = this,
            rating = rating,
            fromUser = false
        )
    }

 data class RatingChangeEvent(
     val view: RatingBar,
     val rating: Float,
     val fromUser: Boolean
)

@CheckResult
@OptIn(ExperimentalCoroutinesApi::class)
 fun RatingBar.ratingChanges() = callbackFlow<Float>  {
    checkMainThread()
    val listener = RatingBar.OnRatingBarChangeListener { _, rating, _ ->
        trySend(rating)
    }
    onRatingBarChangeListener = listener
    awaitClose { onRatingBarChangeListener = null }
}
    .conflate()
    .asInitialValueFlow { rating }

